package com.agile.leetcode.canculateObjectSize.defineAnonymousClassDemo;

import com.agile.leetcode.canculateObjectSize.unsafe.UnsafeUtils;
import com.agile.leetcode.kmp.KMP;
//import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import sun.misc.Unsafe;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 同一类加载器加载的class对弈不一定相同的验证
 * 匿名挂载，jvm虚拟机无法发现
 *
 * @Author ChenZhangKun
 * @Date 2020/12/29 9:22
 */
public class DefineAnonymousClassDemo {
    public static void main(String[] args) throws IOException, IllegalAccessException, InstantiationException {
//        // 拿到底层操作原子类
//        Unsafe unsafe = UnsafeUtils.getUnsafe();
//        int len = 0;
//        // 缓冲区
//        byte[] buffer = new byte[1024];
//        // 文件地址
//        InputStream inputStream = new FileInputStream(new File("E:\\KMP.class"));
//        ByteOutputStream out = new ByteOutputStream();
//        while ((len = inputStream.read(buffer)) != -1) {
//            out.write(buffer, 0, len);
//        }
//        // 转为byte数组
//        byte[] bytes = out.toByteArray();
//        // 加载同意class文件
//        Class<?> aClass = unsafe.defineAnonymousClass(DefineAnonymousClassDemo.class, bytes, null);
//        System.out.println(aClass);
//        // 加载同意class文件
//        Class<?> aClass1 = unsafe.defineAnonymousClass(DefineAnonymousClassDemo.class, bytes, null);
//        System.out.println(aClass1);
//        System.out.println(aClass.getSimpleName());
//        System.out.println(aClass.getClassLoader());
//        System.out.println(aClass1.getClassLoader());
//        KMP o = (KMP) aClass.newInstance();
//        System.out.println(o.getClass());
//        // 同一类加载器加载，但是字节码文件确不相同
//        System.out.println(aClass == aClass1);
    }
}
